let tableIns;
let form;
let element;
let dropdown;
//
let downSourceWeb = []
let downSourceCategory = []
let sourceCategoryMap = new Map();
let sourceWebMap = new Map();
layui.use(['table', 'form', 'element', 'dropdown'], function () {
    form = layui.form;
    element = layui.element;
    dropdown = layui.dropdown;
    let table = layui.table;
    let whereValue = {
        bookTxt: ''
    }
    let auth_token = localStorage.getItem('auth_token');
    let headers = {
        // Basic bearer
        'Authorization': auth_token
    }
    // 创建渲染实例
    tableIns = table.render({
        elem: '#ID-table-book-preview',
        title: '小说预览列表',
        url: '/book/info/v1/queryBookInfoPage',
        method: 'POST',
        // JWT
        headers: headers,
        // 请求参数
        where: whereValue,
        // 数据格式解析的回调函数
        parseData: function (res) {
            let result = {};
            if (res.code === '00000') {
                result = {
                    "code": "0", //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                }
            } else {
                result = {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": 0, //解析数据长度
                    "data": {} //解析数据列表
                }
            }
            return result;
        },
        done: function (res, curr, count) {
            reloadDropdown(headers);
        },
        // 用于开启分页
        page: true,
        // 每页显示的条数
        limit: 15,
        // 每页条数的选择项
        limits: [15, 30, 45, 60],
        // 是否开启隔行背景
        even: true,
        // 请求数据时，是否显示loading
        loading: true,
        //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        cellMinWidth: 100,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            // ID
            {field: 'bookId', fixed: 'left', width: 100, title: 'ID', sort: true, hide: true},
            {field: 'bookWeb', title: '网站源Code', hide: true},
            {field: 'bookWebName', title: '网站源', width: 100},
            {field: 'bookCategory', title: '类别Code', hide: true},
            {field: 'bookCategoryName', width: 100, title: '类别'},
            {field: 'bookTitle', width: 200, title: '标题', templet: '#ID-table-book-preview-title'},
            {field: 'bookIntro', width: 300, title: '简介'},
            {title: '其他', minWidth: 300, templet: '#ID-table-book-preview-other'},
            {field: 'bookLocalPath', title: '电子书本地路径', hide: true},
            {fixed: 'right', title: '操作', minWidth: 200, toolbar: '#operationBar'}

        ]],
        //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
        toolbar: '#toolbarBook', // 开启头部工具栏，并为其绑定左侧模板
        // 头部工具栏右侧图标
        defaultToolbar: ['filter', 'exports', 'print'],
    });

    // 工具栏事件
    table.on('toolbar(test)', function (obj) {
        let id = obj.config.id;
        let checkStatus = table.checkStatus(id);
        let query = {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , done: function (res, curr, count) {
                //完成后重置where，解决下一次请求携带旧数据
                // this.where = {};
            }
        };
        switch (obj.event) {
            case 'getCheckData':
                let data = checkStatus.data;
                layer.alert(layui.util.escape(JSON.stringify(data)));
                break;
            case 'getData':
                let getData = table.getData(id);
                console.log(getData);
                layer.alert(layui.util.escape(JSON.stringify(getData)));
                break;
            case 'LAYTABLE_TIPS':
                layer.alert('自定义工具栏图标按钮');
                break;
            case 'query':
                let bookWebHidden = $("#bookWebHidden").val();
                let bookCategoryHidden = $("#bookCategoryHidden").val();
                let bookTitle = $("#bookTitle").val();
                if (bookWebHidden) {
                    whereValue.bookWeb = bookWebHidden;
                }
                if (bookCategoryHidden) {
                    whereValue.bookCategory = bookCategoryHidden;
                }
                if (bookTitle) {
                    whereValue.bookTxt = bookTitle;
                }
                //设定异步数据接口的额外参数
                query.where = whereValue;
                tableIns.reload(query);
                reloadDropdown(headers);
                if (bookWebHidden) {
                    $('#bookWeb').val(sourceWebMap.get(parseInt(bookWebHidden)));
                    $('#bookWebHidden').val(bookWebHidden);
                }
                if (bookCategoryHidden) {
                    $('#bookCategory').val(sourceCategoryMap.get(parseInt(bookCategoryHidden)));
                    $('#bookCategoryHidden').val(bookCategoryHidden);
                }
                if (bookTitle) {
                    $("#bookTitle").val(bookTitle);
                }
                break;
            case 'reset':
                $("#bookTitle").val('');
                $('#bookCategory').val('');
                $('#bookCategoryHidden').val('');
                $('#bookWeb').val('');
                $('#bookWebHidden').val('');
                whereValue = {};
                break;
            case 'refresh':
                query.where = {};
                $("#bookTitle").val('');
                $('#bookCategory').val('');
                $('#bookCategoryHidden').val('');
                $('#bookWeb').val('');
                $('#bookWebHidden').val('');
                tableIns.reload(query);
                // reloadDropdown(headers);
                break;
        }
        ;
    });

    // 触发单元格右侧工具事件
    table.on('tool(test)', function (obj) { // 双击 toolDouble
        let data = obj.data; // 获得当前行数据
        if (obj.event === 'del') {
            layer.confirm('确认删除吗？', function (index) {
                // 向服务端发送删除指令
                $.delete("/book/info/v1/delete?bookId=" + data.bookId, {}, headers, function (data) {
                    if (data.code === '00000') {
                        layer.msg('删除成功', {icon: 6});
                    } else {
                        layer.msg(data.msg, {icon: 6});
                    }
                    // 表格刷新
                    tableIns.reload();
                    layer.close(index);
                })
            });
        } else if (obj.event === 'edit') {
            bookDetailSub(headers, 'edit', data)
        } else if (obj.event === 'cacheDownload') {
            // if (data.bookLocalPath) {
            //     layer.msg("电子书[" + data.bookTitle + "]已缓存", {icon: 1, time: 2000, offset: 'rb'});
            // } else {
                $.DGet("/book/info/v1/cacheDownloadBook", {bookId: data.bookId}, headers, function (res) {
                    console.log("cacheDownloadBook success");
                    layer.msg("电子书[" + data.bookTitle + "]缓存进行中", {icon: 1, time: 2000, offset: 'rb'});
                });
            }
        // }
    });

});


/**
 * 小说获取
 *
 * @param headers
 * @param type
 * @param bookData
 */
function bookDetailSub(headers, type, bookData) {
    // 重置表单
    $("#bookForm")[0].reset();
    layer.open({
        type: '1',
        content: $('.bookDetailDiv'),
        title: '明细',
        area: ['850px'],
        btn: ['获取', '取消'],
        closeBtn: '1',
        success: function (layero, index) {
            // 回显操作表单
            $("#bookForm").form(bookData);
            form.render();
        },
        btn1: function (index, layero) {
            if (!validateBookCode(layero)) {

            } else {
                //编辑回调
                let bookEditLoadIndex = layer.load(2);
                let bookForm = $("#bookForm").serializeObject();
                // 进度条
                let n = 0, timer = setInterval(function () {
                    n = n + Math.random() * 10 | 0;
                    if (n > 100) {
                        n = 100;
                        clearInterval(timer);
                    }
                    element.progress('bookDownloadProgress', n + '%');
                }, 300 + Math.random() * 1000);
                downloadBook(bookForm, headers, bookEditLoadIndex);
            }
        },
        btn2: function (index, layero) {
            //取消回调
        }
    })
}

/**
 * 下载
 *
 * @param bookForm
 * @param headers
 * @param bookEditLoadIndex
 */
function downloadBook(bookForm, headers, bookEditLoadIndex) {
    $.DGet("/book/info/v1/downloadBook", {
        title: bookForm.bookTitle,
        bookUrl: bookForm.bookUrl
    }, headers, function (data) {
        if (data.code === '00000') {
            layer.msg("获取成功", {icon: 1, time: 200, offset: 'rb'}, function () {
                layer.close(bookEditLoadIndex);
                // 关闭当前页面
                parent.layer.close(parent.layer.getFrameIndex(window.name));
                // 表格刷新
                tableIns.reload();
            });
        } else {
            layer.msg("获取失败", {icon: 1, time: 200, offset: 'rb'}, function () {
                layer.close(bookEditLoadIndex);
                // 关闭当前页面
                parent.layer.close(parent.layer.getFrameIndex(window.name));
                // 表格刷新
                tableIns.reload();
            });
        }

    });
}

function reloadDropdown(headers) {
    $.DGet("/common/v1/queryCommonManyCode", {codes: "10002,10003"}, headers, function (data) {
        // 查询所有司机准备渲染下拉菜单
        if (data.code === '00000') {
            downSourceWeb = data.data[10003];
            downSourceCategory = data.data[10002];
            dropdown.render({
                elem: '#bookCategory' //也可绑定到 document，从而重置整个右键
                , style: 'width: 235px' //定义宽度，默认自适应
                , id: 'id' //定义唯一索引
                , data: downSourceCategory
                , click: function (obj) {
                    // 父节点
                    this.elem.val(obj.title);
                    $('#bookCategoryHidden').val(obj.id);
                }
            });
            dropdown.render({
                elem: '#bookWeb' //也可绑定到 document，从而重置整个右键
                , style: 'width: 235px' //定义宽度，默认自适应
                , id: 'id' //定义唯一索引
                , data: downSourceWeb
                , click: function (obj) {
                    // 父节点
                    this.elem.val(obj.title);
                    $('#bookWebHidden').val(obj.id);
                }
            });
            sourceCategoryMap = downSourceCategory.reduce((acc, cur) => {
                acc.set(cur.id, cur.title);
                return acc;
            }, new Map());
            sourceWebMap = downSourceWeb.reduce((acc, cur) => {
                acc.set(cur.id, cur.title);
                return acc;
            }, new Map());
        }
    });
}

/**
 * 表单验证
 */
function validateBookCode() {
    let bookUrl = $('#bookUrl').val();
    if ($.trim(bookUrl) == '' || $.trim(bookUrl).length <= 0) {
        layer.alert("Book address not found", {icon: 5});
        return false;
    }
    return true;
}


